﻿using DevExpress.Internal.WinApi.Windows.UI.Notifications;
using DevExpress.Mvvm;
using DevExpress.Xpf.Core.FilteringUI;
using FastExpressionCompiler.LightExpression;
using HandyControl.Controls;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.ModelsToLily;
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlaceOrder_Client.ViewModels
{
    /// <summary>
    /// 申请复议的vm
    /// </summary>
    internal class RequestReviewViewModel:BindableBase
    {
        #region 依赖属性
        private string reviewInfoMessage;

        public string ReviewInfoMessage
        {
            get { return reviewInfoMessage; }
            set { reviewInfoMessage = value; RaisePropertiesChanged(); }
        }

        private string orderMessage;
        private YiPingLilyTrade trade;

        public string OrderMessage
        {
            get { return orderMessage; }
            set { orderMessage = value;RaisePropertiesChanged(); }
        }

        #endregion
        public Action CloseWindowAction { get; set; }
        public DelegateCommand CloseWindowCommand { get; set; }

        public List<PlaceOrder_Shared.Models.Common.UserTrade> ReviewTrades { get; set; }
        public RequestReviewViewModel(PlaceOrder_Shared.Models.Common.UserTrade userTrade)
        {
            string brokerInfo = OrderListViewModel.ChatReceivers.Where(o => o.Brokerid == userTrade.BrokerID).FirstOrDefault().Target;
            string command = $"价格：{userTrade.Price},成交量：{userTrade.Volume},类型：{userTrade.OrderType}," +"\r\n"+
                $"清算速度：{userTrade.DeliveryDate},中介：{brokerInfo}";
            this.OrderMessage = $"下单人：{UserHelper.NickName},券号：{userTrade.TsCode}."+ command;
            ReviewTrades=new List<PlaceOrder_Shared.Models.Common.UserTrade> { userTrade };
            ReviewCommand = new DelegateCommand(ReviewToServer);
            CloseWindowCommand = new DelegateCommand(CloseWindow);
        }

        public RequestReviewViewModel(List<PlaceOrder_Shared.Models.Common.UserTrade> userTrade)
        {
            string brokerInfo = null;
            string command;
            int totalItems = userTrade.Count;  // 获取总项数
            if (userTrade.Count==1)
            {
                brokerInfo = OrderListViewModel.ChatReceivers.Where(o => o.Brokerid == userTrade[0].BrokerID).FirstOrDefault().Target;
                command = $"价格：{userTrade[0].Price},类型：{userTrade[0].OrderType},清算速度：{userTrade[0].DeliveryDate},中介：{brokerInfo}";
                this.OrderMessage = $"下单人：{UserHelper.NickName},券号：{userTrade[0].TsCode}." + command;
            }else
            {
                int counter = 1;
                foreach (var item in userTrade)
                {
                    this.OrderMessage += $"询价单据号{counter}: {item.TradeNum}";
                    if (counter < totalItems)
                    {
                        this.OrderMessage += "\r\n";
                    }
                    counter++;
                }
            }

            ReviewTrades = userTrade;

            ReviewCommand = new DelegateCommand(ReviewToServer);
            CloseWindowCommand = new DelegateCommand(CloseWindow);
        }
        private YiPingLilyTrade lilyTrade;
        public RequestReviewViewModel(YiPingLilyTrade userTrade)
        {
            lilyTrade = userTrade;
            string brokerInfo = null;
            string command;
            if(lilyTrade == null)
            {
                return;
            }
            //brokerInfo = userTrade.
            //brokerInfo = OrderListViewModel.ChatReceivers.Where(o => o.Brokerid == userTrade.).FirstOrDefault().Target;
            command = $"已平持仓——价格：{userTrade.Price}，成交量：{userTrade.Volume}，清算速度：{userTrade.DeliverySpeed}" +
                $"\r\n盈亏：{userTrade.Profit}，手续费：{userTrade.RealFee}，询价单据号：{userTrade.UserTradeNum}";
            this.OrderMessage = $"下单人：{UserHelper.NickName}，券号：{userTrade.Tscode}.\r\n" + command;

            ReviewCommand = new DelegateCommand(ReviewYiPingToServer);
            CloseWindowCommand = new DelegateCommand(CloseWindow);
        }

        private async void ReviewYiPingToServer()
        {
            if (string.IsNullOrEmpty(ReviewInfoMessage))
            {
                Growl.ErrorGlobal("请输入复议内容，不能为空！");
                return;
            }
            var chatWorkOrder = new ChatWorkOrder();
            chatWorkOrder.TradeIds.Add( this.lilyTrade.RealTradeId.ToString());
            chatWorkOrder.Remarks = this.ReviewInfoMessage;
            bool result = await UserHelper.ReviewChatWorkOrder(chatWorkOrder);
            if (result)
            {
                Growl.SuccessGlobal($"发送询价单审议消息给审核员成功~");
                AppLog.WriteInfo($"发送询价单审议消息 {ReviewInfoMessage}, 相关TradeIds={string.Join(",", chatWorkOrder.TradeIds.Select(id => id.ToString()))} 给审核员成功~");

            }
            else
            {
                Growl.WarningGlobal($"发送询价单审议消息给审核员失败！");
                AppLog.WriteInfo($"发送询价单审议消息 {ReviewInfoMessage}, 相关TradeIds={string.Join(",", chatWorkOrder.TradeIds.Select(id => id.ToString()))} 给审核员，失败！");
            }

            //Messenger.Default.Send(ReviewInfoMessage, MessageToken.SendReviewMessage);
            CloseWindowAction?.Invoke();
        }

        private async void ReviewToServer()
        {
            if(string.IsNullOrEmpty(ReviewInfoMessage))
            {
                Growl.ErrorGlobal("请输入复议内容，不能为空！");
                return;
            }
            var chatWorkOrder = new ChatWorkOrder();
            chatWorkOrder.TradeIds = this.ReviewTrades
                .Select(o => o.UserTradeID.ToString())
                .ToList();
            chatWorkOrder.Remarks = this.ReviewInfoMessage;
            bool result = await UserHelper.ReviewChatWorkOrder(chatWorkOrder);
            if (result)
            {
                Growl.SuccessGlobal($"发送询价单审议消息给审核员成功~");
                AppLog.WriteInfo($"发送询价单审议消息 {ReviewInfoMessage}, 相关TradeIds={string.Join(",", chatWorkOrder.TradeIds.Select(id => id.ToString()))} 给审核员成功~");

            }else
            {
                Growl.WarningGlobal($"发送询价单审议消息给审核员失败！");
                AppLog.WriteInfo($"发送询价单审议消息 {ReviewInfoMessage}, 相关TradeIds={string.Join(",", chatWorkOrder.TradeIds.Select(id => id.ToString()))} 给审核员，失败！");
            }

            //Messenger.Default.Send(ReviewInfoMessage, MessageToken.SendReviewMessage);
            CloseWindowAction?.Invoke();
        }

        // 关闭窗口的方法
        private void CloseWindow()
        {
            CloseWindowAction?.Invoke();
        }

        public DelegateCommand ReviewCommand { get;set; }
    }
}
